package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.*;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.MovementService;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@DubboService
public class MovementServiceImpl implements MovementService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;//全局id自增器



    @Override
    public void save(Movement movement) {
        //0.给动态设置一个pid(大数据团队用)
        movement.setPid(redisIdService.getNextId(ConstantUtil.MOVEMENT_ID));

        //获取userid
        Long userId = movement.getUserId();

        //1.保存到动态详情表
        mongoTemplate.save(movement);

        //2.封装个人动态对象,保存到我的动态表中
        MyMovement myMovement = new MyMovement();
        myMovement.setPublishId(movement.getId());//设置动态id
        myMovement.setCreated(movement.getCreated());//设置时间

        mongoTemplate.save(myMovement,ConstantUtil.MOVEMENT_MINE+userId);//往自己movement表中放 我的动态

        //3.封装好友动态对象
        FriendMovement friendMovement = new FriendMovement();
        friendMovement.setUserId(userId);
        friendMovement.setPublishId(movement.getId());
        friendMovement.setCreated(movement.getCreated());

        //4.查询好友列表,遍历集合,获取到每个好友,往好友的 好友动态表中 存放 好友动态对象(我的好友 的好友 就是我,即friend.getFriendId())
        Query query = new Query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query,Friend.class);

        if (CollUtil.isNotEmpty(friends)) {
            friends.forEach(friend -> {
                mongoTemplate.save(friendMovement,ConstantUtil.MOVEMENT_FRIEND+friend.getFriendId());
            });
        }
    }

    @Override
    public PageBeanVo findMyMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.构建查询对象
        Query query = new Query();

        //2.查询我的动态表中总记录数
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_MINE + userId);

        //3.往查询对象上追加条件(分页和排序)
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询我的动态表中数据--只有动态id
        List<MyMovement> myMovements = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        //5.遍历我的动态list,获取每个动态id,再去动态表中查询动态详情,将每个详情给放入一个movementList中
        //5.1 创建movementList
        List<Movement> movementList = new ArrayList<>();

        //5.2 遍历我的动态list,获取每个动态id
        if (CollUtil.isNotEmpty(myMovements)) {
            myMovements.forEach(myMovement -> {
                //5.3 再去动态表中查询动态详情
                Movement movement = mongoTemplate.findById(myMovement.getPublishId(), Movement.class);
                //5.4 将每个(已经过审核)的详情给放入一个movementList中
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            });
        }

        //6.封装PageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public PageBeanVo findFriendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.构建查询对象
        Query query = new Query();

        //2.查询我的好友动态表中总记录数
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_FRIEND + userId);

        //3.往查询对象上追加条件(分页和排序)
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询我的好友动态表中当前页的list--只有动态id
        List<FriendMovement> friendMovements = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);

        //5.遍历好友动态集合,获取每个动态id,查询动态详情表获取动态详情,将动态详情放入一个movementList中
        List<Movement> movementList = new ArrayList<>();

        //遍历好友动态list,获取每个动态id
        if (CollUtil.isNotEmpty(friendMovements)) {
            friendMovements.forEach(friendMovement -> {
                //再去动态表中查询动态详情
                Movement movement = mongoTemplate.findById(friendMovement.getPublishId(), Movement.class);

                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            });

        }

        //6.封装PageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public PageBeanVo findRecommendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.构建查询对象(推荐给我的)
        Query query = new Query(Criteria.where("userId").is(userId));

        //2.查询推荐动态表中总记录数
        long count = mongoTemplate.count(query, RecommendMovement.class);

        //3.往查询对象上追加条件(分页和排序)
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询推荐动态表中数据--只有动态id
        List<RecommendMovement> recommendMovements = mongoTemplate.find(query, RecommendMovement.class);

        //5.遍历推荐动态list,获取每个动态id,再去动态表中查询动态详情,将每个详情给放入一个movementList中
        //5.1 创建movementList
        List<Movement> movementList = new ArrayList<>();

        //5.2 遍历我的动态list,获取每个动态id
        if (CollUtil.isNotEmpty(recommendMovements)) {
            recommendMovements.forEach(recommendMovement -> {
                //5.3 再去动态表中查询动态详情
                Movement movement = mongoTemplate.findById(recommendMovement.getPublishId(), Movement.class);
                //5.4 将每个(已经过审核)的详情给放入一个movementList中
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            });
        }

        //6.封装PageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public Movement findById(ObjectId id) {
        return mongoTemplate.findById(id,Movement.class);
    }


    @Override
    public PageBeanVo  findMovementByCondition4Page(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        //1.创建条件查询对象
        Query query = new Query();
        //2.判断userId是否为空,若不为空就添加userId条件,查询指定用户的动态表,获取其总记录数和当前页的数据集合,有了集合后还需要查询movement表,查询详情集合.
        if (userId != null) {
            //2.查询我的动态表中总记录数
            long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_MINE + userId);

            //3.往查询对象上追加分页和排序
            query.skip((pageNum-1)*pageSize).limit(pageSize)
                    .with(Sort.by(Sort.Order.desc("created")));

            //4.查询我的动态表中数据--只有动态id
            List<MyMovement> myMovements = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

            //5.遍历我的动态list,获取每个动态id,再去动态表中查询动态详情,将每个详情给放入一个movementList中
            //5.1 创建movementList
            List<Movement> movementList = new ArrayList<>();

            //5.2 遍历我的动态list,获取每个动态id
            if (CollUtil.isNotEmpty(myMovements)) {
                myMovements.forEach(myMovement -> {
                    //5.3 再去动态表中查询动态详情
                    Movement movement = mongoTemplate.findById(myMovement.getPublishId(), Movement.class);

                    //5.4 把movement加入到预先声明的list中
                    movementList.add(movement);
                });
            }

            //6.封装PageBeanVo且返回
            return new PageBeanVo(pageNum,pageSize,count,movementList);
        }else if(state != null){
            //3.判断state是否为空,若不为空就添加state条件,查询动态表中的总记录数和当前页的数据集合.
            query.addCriteria(Criteria.where("state").is(state));

            return findMovementByState(pageNum, pageSize, query);
        }else {
            return findMovementByState(pageNum,pageSize,query);
        }

    }



    private PageBeanVo findMovementByState(Integer pageNum, Integer pageSize, Query query) {
        //查询动态表中的总记录数
        long count = mongoTemplate.count(query, Movement.class);

        //查询当前页的数据集合.
        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum -1)* pageSize).limit(pageSize);
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        return new PageBeanVo(pageNum, pageSize,count,movementList);
    }


    @Override
    public void update(Movement movement) {
        mongoTemplate.save(movement);
    }


}